﻿using System;
using System.Collections.Generic;
using EasySL.Share;
using System.Windows.Browser;
using EasySL.Controls;

namespace EasySL.Core
{
    public class Requestor
    {    
        public void GetDataAsync(Request request, Type type, object state, GetDataAsyncCompleted callback)
        {                      
            string jsonString = request.Serialize();
            jsonString = HttpUtility.UrlEncode(jsonString);
            //jsonString = jsonString.Replace("+", "%2B");
            this.currentRequest = request;
            this.currentState = state;
            this.currentType = type;
            this.currentCallback = callback;

            HttpHelper helper = new HttpHelper(new Uri(requestHandleUrl), "POST",
                new KeyValuePair<string, string>("request", jsonString));
            helper.ResponseComplete += new HttpResponseCompleteEventHandler(helper_ResponseComplete);
            helper.Execute();
        }

        void helper_ResponseComplete(HttpResponseCompleteEventArgs e)
        {
            Response response = new Response();
            response.Deserialize(e.Response, this.currentType);
            response.State = this.currentState;

            if (response.Status == ResponseStatus.ServiceException)
            {
                Window.Alert(string.Format("{0}:\r\n{1}", currentRequest.MethodName, response.Message));
                Window.HideLoading();
                return;
            }

            if (this.currentCallback != null)
                currentCallback(response);
        }

        private static string GetServiceUrl(string url)
        {
            Uri uri = new Uri(HtmlPage.Document.DocumentUri, url);
            return uri.AbsoluteUri;
        }

        public static Requestor Instance()
        {
            if (instance == null)
                instance = new Requestor();

            return instance;
        }

        private static readonly string requestHandleUrl = GetServiceUrl("GetData.asmx");
        private Type currentType;
        private object currentState;
        private Request currentRequest;
        private GetDataAsyncCompleted currentCallback;
        private static Requestor instance;
    }

    public delegate void GetDataAsyncCompleted(Response response);
}
